var express = require('express');
var router = express.Router();
const { Course, Category, User, Chapter } = require('../../models');
const { Op } = require('sequelize');

router.get('/', async function(req, res, next) {
  try {
    const { categoryId, userId, name, recommended, introductory } = req.query;
    const currentPage = parseInt(req.query.currentPage) || 1; // 当前页码，默认为 1
    const pageSize = parseInt(req.query.pageSize) || 10; // 每页数量，默认为 10
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      attributes: { exclude: ['CategoryId', 'UserId'] }, // 排除字段
      where: {}, // 查询条件
      // 关联模型
      include: [
        {
          model: Category,
          as: 'category',
          attributes: ['id', 'name'] // 只查询分类的 id 和 name 字段
        },
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username']
        }
      ],
      order: [['id', 'DESC']], // 按照 id 降序排列
      limit: pageSize,
      offset: offset
    }
    if (categoryId) {
      condition.where.categoryId = {
        [Op.eq]: categoryId
      }
    }
    if (userId) {
      condition.where.userId = {
        [Op.eq]: userId
      }
    }
    if (name) {
      condition.where.name = {
        [Op.like]: `%${name}%` // 模糊查询
      }
    }
    if (recommended) {
      condition.where.recommended = {
        [Op.eq]: recommended === 'true'
      }
    }
    if (introductory) {
      condition.where.introductory = {
        [Op.eq]: introductory === 'true'
      }
    }
    // 查询所有课程
    const { rows, count } = await Course.findAndCountAll(condition)
    res.json({
      status: true,
      message: 'Course route',
      data: {
        Courses: rows,
        pagination: {
          pageSize,
          currentPage,
          total: count
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to fetch Courses',
      error: [error.message]
    });
  }
});

router.get('/:id', async function(req, res, next) {
  try {
    const { id } = req.params;
    const condition = {
      attributes: { exclude: ['CategoryId', 'UserId'] },
      include: [
        {
          model: Category,
          as: 'category',
          attributes: ['id', 'name']
        },
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username']
        }
      ]
    }
    // 查询主键 id 的课程
    const course = await Course.findByPk(id, condition);
    if (!course) {
      return res.status(404).json({
        status: false,
        message: 'course not found',
      });
    }
    res.json({
      status: true,
      message: 'course fetched successfully',
      data: {
        course
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to fetch Course',
      error: [error.message]
    });
  }
})

router.post('/', async function(req, res, next) {
  try {
    const body = filterBody(req.body)
    body.userId = req.user.id; // 设置当前用户为课程创建者
    const Course = await Course.create(body);
    res.status(201).json({
      status: true,
      message: 'Course created successfully',
      data: {
        Course
      }
    });
  } catch (error) {
    if (error.name === 'SequelizeValidationError') {
      return res.status(400).json({
        status: false,
        message: '请求参数错误',
        error: error.errors.map(err => err.message)
      });
    } else {
      res.status(500).json({
        status: false,
        message: 'Failed to create Course',
        error: [error.message]
      });
    }
  }
})

router.delete('/:id', async function(req, res, next) {
  const { id } = req.params;
  try {
    const chapterCount = await Chapter.count({ where: { courseId: id  } });
    if (chapterCount > 0) {
      throw new Error('当前课程有章节，不能删除');
    }
    const Course = await Course.findByPk(id);
    if (!Course) {
      return res.status(404).json({
        status: false,
        message: 'Course not found',
      });
    }
    await Course.destroy();
    res.json({
      status: true,
      message: 'Course deleted successfully',
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to delete Course',
      error: [error.message]
    });
  }
})

router.put('/:id', async function(req, res, next) {
  const { id } = req.params;
  try {
    const Course = await Course.findByPk(id);
    if (!Course) {
      return res.status(404).json({
        status: false,
        message: 'Course not found',
      });
    }
    await Course.update(filterBody(req.body));
    res.json({
      status: true,
      message: 'Course update successfully',
      data: {
        Course
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to update Course',
      error: [error.message]
    });
  }
})

function filterBody(body) {
  const {
    categoryId, name,
    image, recommended, introductory,
    content
  } = body;
  return {
    categoryId,
    name,
    image,
    recommended,
    introductory,
    content
  };
}

module.exports = router;
